//
//  StaffSearchViewController.m
//  Manager
//
//  Created by Mr.Lee on 2018/6/1.
//  Copyright © 2018年 Reabam. All rights reserved.
//

#import "StaffSearchViewController.h"
#import "LoginViewController.h"
#import "UIButton+WebCache.h"
#import "RDVTabBarController.h"
#import "MJRefresh.h"
#import "ClerkManagerListCell.h"
#import "StoreAssistantModel.h"
#import "TSFooterRefresh.h"
#import "TSHeaderRefresh.h"
#import "ClerkManagerViewController.h"
#import "IdentityChangeViewController.h"


@interface StaffSearchViewController ()<UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, ClerkManagerListCellDelegate, UIGestureRecognizerDelegate>
{
    UITextField *searchTextField;
    UIView *myToolBar;
    NSMutableArray*modelArray;
    int pageNumber;
    NSString *result;
    UITableView *table;
    UIView*noDataView;
}
@property (nonatomic, weak) UILabel *headerTitleLabel;
//@property (weak, nonatomic)  UITableView *tableV;
@property(nonatomic,strong)NSIndexPath *lastPath;
@end

@implementation StaffSearchViewController
{
    NSInteger current;
}
- (void)BackAction:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden=YES;
    [searchTextField becomeFirstResponder];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =[UIColor whiteColor];
    current = -1;
    modelArray = [NSMutableArray array];
    [self setUpTopView];
    [self setUpTabelList];
    
}

- (void)setUpTopView{
    UIView *topViewP = [[UIView alloc] init];
    topViewP.frame = CGRectMake(0, 0, ScreenWidth, StatusBarAndNavigationBarHeight);
    topViewP.backgroundColor = lanse;
    [self.view addSubview:topViewP];
    
    UIView *topView = [[UIView alloc] init];
    topView.frame = CGRectMake(0, StatusBarHeight, ScreenWidth, 44);
    topView.backgroundColor = lanse;
    [topViewP addSubview:topView];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    UIImage *tinted = [backImage rt_tintedImageWithColor:[UIColor whiteColor]];
    
    UIButton* backButton= [[UIButton alloc] init];
    backButton.frame = CGRectMake(0, 0, 58, 44);
    [backButton setImage:tinted forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:backButton];
    
    UIView *topLineView = [[UIView alloc] init];
    topLineView.frame = CGRectMake(0, topView.height-0.5, ScreenWidth, 1);
    topLineView.backgroundColor = [UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0];
//    [topView addSubview:topLineView];
    
    myToolBar=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, viewheight)];
    myToolBar.backgroundColor=jianpancolor;
    UIButton*  tubtnDone=[[UIButton alloc]initWithFrame:CGRectMake(logoX,logoY, logoheight, logowidth)];
    [tubtnDone setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [tubtnDone addTarget:self action:@selector(OnTapDone1) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:tubtnDone];
    UIButton*btnDone111=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width - 55, 12, 40, 16)];
    [btnDone111 setTitle:@"搜索" forState:UIControlStateNormal];
    [btnDone111 setTitleColor:jianpancolor1 forState:UIControlStateNormal];
    btnDone111 .titleLabel .font=[UIFont systemFontOfSize:keyboardFot];
    [btnDone111 addTarget:self action:@selector(OnTapDone1) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:btnDone111];
    myToolBar.alpha=alp;
    UIButton* dabtn=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width-60, 0, 60, 40)];
    [dabtn addTarget:self action:@selector(OnTapDone1) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:dabtn];
    
    UIView *sousuoView=[[UIView alloc]initWithFrame:CGRectMake(backButton.right-5, (topView.height- 65/2)*0.5, ScreenWidth- backButton.width-15+5, 65/2)];
    sousuoView.backgroundColor = [UIColor colorWithRed:82/255.0 green:180/255.0 blue:236/255.0 alpha:0.36];
    sousuoView.layer.cornerRadius = 15.0;
    sousuoView.layer.masksToBounds = YES;
    [topView addSubview:sousuoView];
    
    UIImage* fangdajing = [UIImage imageNamed:@"sousuo"];
    UIImage *fangdajingNew = [fangdajing rt_tintedImageWithColor:[UIColor colorWithHexString:@"92cff3"]];
    UIButton *screenBtnIM = [[UIButton alloc] initWithFrame:CGRectMake(10, 4, 50/2, 50/2)];
    [screenBtnIM setImage:fangdajingNew forState:UIControlStateNormal];
    [sousuoView addSubview:screenBtnIM];
    
    searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(screenBtnIM.right+5, 1, sousuoView.width-screenBtnIM.right -10,65/2)];
    [searchTextField setBorderStyle:UITextBorderStyleNone]; //外框类型
    searchTextField.placeholder = @"请输入店员姓名/手机号搜索"; //默认显示的字
    searchTextField.font = [UIFont systemFontOfSize:14.0];
    [searchTextField setValue:[UIColor colorWithHexString:@"92cff3"] forKeyPath:@"_placeholderLabel.textColor"];
    searchTextField.tag=22;
    searchTextField.returnKeyType = UIReturnKeySearch;
    searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
    searchTextField.delegate = self;
    searchTextField.tintColor = [UIColor colorWithHexString:@"92cff3"];//光标颜色;
    searchTextField.textColor = [UIColor whiteColor];   // 输入文字颜色
    searchTextField.inputAccessoryView = myToolBar;
    [searchTextField addTarget:self action:@selector(inputFiled:) forControlEvents:UIControlEventEditingChanged];
    [sousuoView addSubview:searchTextField];
}

- (void)setUpTabelList {
    
    UIView *headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 64, ScreenWidth, 40);
    headerView.backgroundColor = lanse1;
    UILabel *headerTitleLabel = [[UILabel alloc] init];
    self.headerTitleLabel = headerTitleLabel;
    headerTitleLabel.frame = CGRectMake(10, 0, ScreenWidth-30, 40);
    headerTitleLabel.font = [UIFont systemFontOfSize:14.0];
    headerTitleLabel.textColor = [UIColor colorWithHexString:@"0880c6"];
    [headerView addSubview:headerTitleLabel];
//    [self.view addSubview:headerView];
    
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, StatusBarAndNavigationBarHeight, ScreenWidth, ScreenHeight- StatusBarAndNavigationBarHeight) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:table];
    
    UIView*foot=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    foot.backgroundColor=[UIColor whiteColor];
    table.tableFooterView=foot;
    
    
    UITapGestureRecognizer *tableViewGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableViewTouchInSide)];
    tableViewGesture.numberOfTapsRequired = 1; //几个手指点击
    tableViewGesture.delegate = self;
    tableViewGesture.cancelsTouchesInView = NO;//是否取消点击处的其他action
    [table addGestureRecognizer:tableViewGesture];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:[UITableView class]]) {
        return YES;
    }
    return  NO;
}
- (void)tableViewTouchInSide {
    [self oldCellMoreViewHide];
}
    
    


- (void)textFieldDidEndEditing:(UITextField *)textField{
    [searchTextField resignFirstResponder];
}
- (BOOL)textFieldShouldClear:(UITextField *)textField{
    [searchTextField resignFirstResponder];
    searchTextField.text = nil;
    [modelArray removeAllObjects];
    [table reloadData];
    return YES;
}
- (void)inputFiled:(UITextField *)tf{
    if (tf.text.length == 0) {
        NSLog(@"---");
        searchTextField.text = nil;
        [modelArray removeAllObjects];
        [table reloadData];
//        [searchTextField resignFirstResponder];
    }
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [searchTextField resignFirstResponder];
    if (textField.text.length >0) {
        NSString *serchWord = textField.text;
        [self requeststaffWithKeyWord:serchWord];
    } else{
        searchTextField.text = nil;
        [modelArray removeAllObjects];
        [table reloadData];
    }

    return YES;
    
}

-(void)OnTapDone1{
    [searchTextField resignFirstResponder];
    if (searchTextField.text.length >0) {
        NSString *serchWord = searchTextField.text;
        [self requeststaffWithKeyWord:serchWord];
    }
}

- (void)requeststaffWithKeyWord:(NSString *)keyWord{
    
    [modelArray removeAllObjects];
    NSString *Token = [UserDefaults objectForKey:@"tokenId"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"tokenId"];
    [params setValue:self.companyId forKey:@"companyId"];
    [params setValue:keyWord forKey:@"sword"];
    NSLog(@"-----params---- %@", params);
    [MBProgressHUD showIndeterminateHudSub:@"加载中，请稍候。。。" delay:30 view:self.view];
    [HttpRequest requestData:@"manage/findSysstaffList" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        NSLog(@"findSysStaffCompList====%@",severDataDict.dataDict);
        if (isSuccess) {
            [MBProgressHUD hideProgressHUDInternal:self.view];
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                NSMutableArray *dataArr = [severDataDict.dataDict objectForKey:@"users"];
                
                if (dataArr.count >0) {
                    for (NSDictionary* dicc in dataArr ){
                        StoreAssistantModel *model = [StoreAssistantModel mj_objectWithKeyValues:dicc];
                        [modelArray addObject:model];
                    }
                    [table reloadData];
                    self.headerTitleLabel.text = [NSString stringWithFormat:@"共 %ld 个商户", dataArr.count];
                }
                
                
                
            } else {
                [MBProgressHUD hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
                
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    LoginViewController *loginVC = [[LoginViewController alloc] init];
                    [self.navigationController pushViewController:loginVC animated:YES];
                }
            }
        } else {
            [MBProgressHUD hideProgressHUDInternal:self.view];
            [MBProgressHUD showTextHudSub:severDataDict.resultStr view:self.view];
        }
    }];
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return modelArray.count;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return  90;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    StoreAssistantModel *model = modelArray[indexPath.row];
    
    static NSString *CellIdentifier = @"cell2";
    ClerkManagerListCell *cell = ( ClerkManagerListCell *)[tableView dequeueReusableCellWithIdentifier: CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"ClerkManagerListCell" owner:nil options:nil] lastObject];
    }
    
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.index = indexPath ;
    cell.model = model;
    
    NSInteger row = [indexPath row];
    NSInteger oldRow = [self.lastPath row];
    if (row == oldRow && self.lastPath!=nil) {
        cell.moreView.hidden = NO;
        [cell moreViewShowWithNoAnimate];
    }else{
        cell.moreView.hidden  = YES;
        [cell moreViewHide];
    }
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//    StaffCompListModel *model = modelArray[indexPath.row];
//    ClerkManagerViewController *storeInforVC = [[ClerkManagerViewController alloc] init];
//    storeInforVC.companyId = model.companyId;
//    storeInforVC.titleName = model.companyName;
//    storeInforVC.view.backgroundColor = [UIColor whiteColor];
//    [self.navigationController pushViewController:storeInforVC animated:YES];
    [self oldCellMoreViewHide];
}


- (void)clickMoreBtn:(NSIndexPath *)index{
    NSInteger newRow = [index row];
    NSInteger oldRow = (self .lastPath !=nil)?[self .lastPath row]:-1;
    if (newRow != oldRow) {
        ClerkManagerListCell *newCell = ( ClerkManagerListCell *)[table cellForRowAtIndexPath:index];
        [newCell moreViewShow];
        ClerkManagerListCell *oldCell = ( ClerkManagerListCell *)[table cellForRowAtIndexPath:self.lastPath];
        [oldCell moreViewHide];
        self.lastPath = index;
    } else{
        ClerkManagerListCell *newCell = ( ClerkManagerListCell *)[table cellForRowAtIndexPath:index];
        [newCell moreViewShow];
        self.lastPath = index;
    }
    [table deselectRowAtIndexPath:index animated:YES];
}

#pragma mark -- ClerkManagerListCellDelegate
// 点击启用
- (void)leftBtnClick:(NSIndexPath *)index{
    [self oldCellMoreViewHide];
    StoreAssistantModel *model = modelArray[index.row];
    [self updateStateOrIdentityRequestWithscID:model.scId andStatus:@"Y"];
}
// 点击停用
- (void)middleBtnClick:(NSIndexPath *)index{
    [self oldCellMoreViewHide];
    StoreAssistantModel *model = modelArray[index.row];
    [self updateStateOrIdentityRequestWithscID:model.scId andStatus:@"N"];
}

//点击身份变更
- (void)rightBtnClick:(NSIndexPath *)index{
    [self oldCellMoreViewHide];
    [searchTextField resignFirstResponder];
    // 身份变更
    IdentityChangeViewController *identiChange = [[IdentityChangeViewController alloc] init];
    StoreAssistantModel *model = modelArray[index.row];
    __weak typeof(self) weakself = self;
    identiChange.IdentityChangeViewControllerBlock = ^(NSString *identityString){
        [weakself requeststaffWithKeyWord:searchTextField.text];
    };
    identiChange.titleName = model.userTypeName;
    identiChange.userType = model.userType;
    identiChange.scId = model.scId;
    identiChange.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:identiChange animated:YES];
    
}

// 审核
- (void)gotoCheckIdentity:(NSIndexPath *)index{
    [searchTextField resignFirstResponder];
    
    StoreAssistantModel *model = modelArray[index.row];
    NSLog(@"%ld---%ld", index.section, index.row);
    //显示弹出框列表选择
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否确认通过审核?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction* saveAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
        //响应事件
        NSLog(@"action = %@", action);
        //        StoreAssistantModel *model = self.modelArray[index.row];
        [self updateStateOrIdentityRequestWithscID:model.scId andStatus:@"Y"];
    }];
    
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
        //响应事件
        NSLog(@"action = %@", action);
    }];
    
    [cancleAction setValue:[UIColor lightGrayColor] forKey:@"titleTextColor"];
    
    [alert addAction:cancleAction];
    [alert addAction:saveAction];
    [self presentViewController:alert animated:YES completion:nil];
    
}

// 移除'更多操作'
- (void)oldCellMoreViewHide{
    ClerkManagerListCell *oldCell = ( ClerkManagerListCell *)[table cellForRowAtIndexPath:self.lastPath];
    [oldCell moreViewHide];
    self.lastPath = nil;
}

// 修改店员状态或者身份
- (void)updateStateOrIdentityRequestWithscID:(NSString *)scId andStatus:(NSString *)status{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"tokenId"];
    [params setValue:scId forKey:@"scId"];
    [params setValue:status forKey:@"status"];
    NSLog(@"params ==== %@",params);
    [HttpRequest requestData:@"manage/auditUser" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        NSLog(@"====%@",severDataDict.dataDict);
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [MBProgressHUD hideProgressHUDInternal:self.view];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"UPDATECOMPANYLIST" object:nil];
                // 刷新数据
                [self requeststaffWithKeyWord:searchTextField.text];
                
                
                
            }else{
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [MBProgressHUD showTextHud:requestResultStr view:self.view];
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    
                    LoginViewController* Login=[[LoginViewController alloc]init];
                    [self.navigationController pushViewController:Login animated:YES];
                    
                }
            }
        } else {
            [MBProgressHUD hideProgressHUDInternal:self.view];
            [MBProgressHUD showTextHudSub:severDataDict.resultStr view:self.view];
        }
        
    }];
    
}

@end
